

/**
 * Created by sunchenglin on 2017/7/4.
 * 给定一颗二叉搜索树，请找出其中的第k大的结点。例如， 5 / \ 3 7 /\ /\ 2 4 6 8 中，按结点数值大小顺序第三个结点的值为4。
 *
 */
public class Solution {

    int count = 0;
    TreeNode result = null;
    TreeNode KthNode(TreeNode pRoot, int k)
    {
        if (k<=0)
            return null;
        if(pRoot!=null)
        {
            if(pRoot.left!=null){
                KthNode(pRoot.left, k);
            }
            if(++count == k){
                result = pRoot;
                return result;
            }
            if(pRoot.right!=null){
                KthNode(pRoot.right, k);
            }
        }
        return result;
    }

    public static void main(String args[]){
        Solution s = new Solution();
        TreeNode node1 = new TreeNode(1);
        TreeNode node2 = new TreeNode(2);
        TreeNode node3 = new TreeNode(3);
        TreeNode node4 = new TreeNode(4);
        TreeNode node5 = new TreeNode(5);
        TreeNode node6 = new TreeNode(6);
        TreeNode node7 = new TreeNode(7);
        TreeNode node8 = new TreeNode(8);

        node1.left = node2;
        node1.right = node3;
        node2.left = node4;
        node2.right = node5;
        node3.left = node7;
        node3.right = node8;

        System.out.println(s.KthNode(node1,3).val);
    }
}

class TreeNode {
    int val = 0;
    TreeNode left = null;
    TreeNode right = null;

    public TreeNode(int val) {
        this.val = val;

    }

}
